/*
 * @Description:
 * @Author: Rfan
 * @Date: 2022-04-28 13:48:21
 * @LastEditTime: 2023-02-01 10:54:36
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, message, Table } from 'antd';
import { observer } from 'mobx-react-lite';
import { formatDate, isNullObj } from '@/utils';

import { useBusinessGuidanceContext } from '../contexts/BusinessGuidanceContext';
import Guidance from './dialogs/Guidance';
import { useGuidanceTypeContext } from '../contexts/GuidanceWaysContext';
import Feedback from './dialogs/Feedback';
import { arraignmentAnnualById } from '@/api/onlineAndVirtual/annualInspection';
import Inspection from './dialogs/Inspection';
import UpLoadBusiness from './dialogs/UpLoadBusiness';

const { Column } = Table;

const PageList = (props: any) => {
  const { className, instructedUnitId } = props;
  const { type } = useGuidanceTypeContext();
  const {
    selectItems,
    setSelectKey,
    getEnclosure,
    businessList,
    getBusinessList,
    resultFilter,
    enclosure,
    readGuidance,
    readFilter,
    sendStatus
  } = useBusinessGuidanceContext();
  const [guidanceVisible, setGuidanceVisible] = useState(false);
  const [upDataVisible, setUpDataVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);

  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });

  useEffect(() => {
    if (instructedUnitId) {
      const param = type === 3 ? { instructedUnitId } : { type, instructedUnitId };
      if (sendStatus.sendStatus === 0 || JSON.stringify(sendStatus) === '{}') {
        if (sendStatus.year !== 'Invalid Date') {
          setListQuery({
            pageNo: 1,
            pageSize: 10,
            param: { ...param, year: sendStatus.year }
          });
        } else {
          setListQuery({
            pageNo: 1,
            pageSize: 10,
            param: { ...param }
          });
        }
      } else {
        if (sendStatus.year === 'Invalid Date') {
          delete sendStatus.year;
        }
        setListQuery({
          pageNo: 1,
          pageSize: 10,
          param: { ...param, ...sendStatus }
        });
      }
    }
  }, [instructedUnitId, sendStatus]);

  useEffect(() => {
    if (listQuery && !isNullObj(listQuery.param)) {
      setLoading(true);
      getBusinessList(listQuery, type)
        .then((res: any) => {
          setTotal(res?.totalCount);
          setTimeout(() => {}, 2000);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  /**
   * @description : 表格选项相关设置
   * @param {number} selectedRowKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectKey(selectedRowKeys);
  };

  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };
  /* 查看传来内容 */
  const ToReadGuidance = (value: any) => {
    type === 3
      ? getEnclosure(value.id, type).then(setGuidanceVisible(true))
      : readGuidance(value.id).then(getEnclosure(value.id, type).then(setGuidanceVisible(true)));
  };
  /* 修改年审 */
  const ToGuidance = (value: any) => {
    getEnclosure(value.id, type).then(setUpDataVisible(true));
  };
  return (
    <div className={className}>
      <Table
        dataSource={businessList}
        loading={loading}
        rowKey="id"
        rowSelection={rowSelection}
        bordered
        scroll={{ x: 'max-content' }}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
      >
        <Column title="序号" dataIndex="id" key="id" align="center" />
        <Column
          title={type === 1 ? '指导单名称' : type === 2 ? '书面反馈名称' : '年检名称'}
          dataIndex="name"
          key="name"
          align="center"
        />
        {type !== 3 && (
          <>
            <Column
              title="指导单位"
              dataIndex="instructedUnitName"
              key="instructedUnitName"
              align="center"
            />
            <Column title="指导员" dataIndex="operatorName" key="operatorName" align="center" />
            <Column
              title="接收时间"
              dataIndex="sendTime"
              key="sendTime"
              align="center"
              render={(text) => <span>{formatDate(text)}</span>}
            />
            <Column
              title="状态"
              dataIndex="readStatus"
              key="readStatus"
              align="center"
              render={(status, record: any) => <>{resultFilter(status)}</>}
            />
            <Column
              title="操作"
              key="action"
              align="center"
              render={(_text, record: any) => (
                <Button type="link" onClick={() => ToReadGuidance(record)}>
                  {type === 1 ? '查看指导意见' : '查看书面反馈'}
                </Button>
              )}
            />
          </>
        )}
        {type === 3 && (
          <>
            <Column title="年度" dataIndex="year" key="year" align="center" />
            <Column
              title="审核单位"
              dataIndex="guidanceUnitName"
              key="guidanceUnitName"
              align="center"
            />
            <Column
              title="创建时间"
              dataIndex="createTime"
              key="createTime"
              align="center"
              render={(text) => <span>{formatDate(text)}</span>}
            />
            <Column title="创建人" dataIndex="operatorName" key="operatorName" align="center" />
            <Column
              title="发送时间"
              dataIndex="sendTime"
              key="sendTime"
              align="center"
              width={120}
              render={(text) => <span>{formatDate(text)}</span>}
            />
            <Column
              title="审核人"
              dataIndex="checkPersonName"
              key="checkPersonName"
              align="center"
            />
            <Column
              title="审核时间"
              dataIndex="checkTime"
              key="checkTime"
              align="center"
              width={120}
              render={(text) => <span>{formatDate(text)}</span>}
            />
            <Column
              title="状态"
              dataIndex="sendStatus"
              key="sendStatus"
              align="center"
              render={(status, record: any) => <>{readFilter(status)}</>}
            />
            <Column
              title="操作"
              key="action"
              align="center"
              render={(_text, record: any) => (
                <>
                  {[1, 2, 3].includes(record.sendStatus) && (
                    <>
                      <Button
                        type="link"
                        disabled={record.sendStatus !== 1}
                        onClick={() => ToGuidance(record)}
                      >
                        编辑
                      </Button>
                      <Button
                        type="link"
                        disabled={record.sendStatus !== 1}
                        onClick={() =>
                          arraignmentAnnualById(record.id).then(message.info('发送成功'))
                        }
                      >
                        发送
                      </Button>
                    </>
                  )}
                  {[4, 5].includes(record.sendStatus) && (
                    <Button type="link" onClick={() => ToReadGuidance(record)}>
                      审核反馈详情
                    </Button>
                  )}
                </>
              )}
            />
          </>
        )}
      </Table>
      {useMemo(
        () =>
          type === 1 &&
          enclosure && (
            <Guidance
              visible={guidanceVisible}
              enclosure={enclosure}
              onClose={() => {
                setGuidanceVisible(false);
              }}
            />
          ),
        [guidanceVisible, enclosure]
      )}
      {useMemo(
        () =>
          type === 2 &&
          enclosure && (
            <Feedback
              visible={guidanceVisible}
              enclosure={enclosure}
              onClose={() => {
                setGuidanceVisible(false);
              }}
            />
          ),
        [guidanceVisible, enclosure]
      )}
      {useMemo(
        () =>
          type === 3 &&
          enclosure && (
            <Inspection
              visible={guidanceVisible}
              enclosure={enclosure}
              onClose={() => {
                setGuidanceVisible(false);
              }}
            />
          ),
        [guidanceVisible, enclosure]
      )}
      {useMemo(
        () => (
          <UpLoadBusiness
            visible={upDataVisible}
            data={enclosure}
            onClose={() => {
              setUpDataVisible(false);
            }}
          />
        ),
        [upDataVisible, enclosure]
      )}
    </div>
  );
};

export default observer(PageList);
